from django.db import models
from hashlib import md5
from django.utils import six, timezone
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.signals import user_logged_in


class BaseModel(models.Model):

    @classmethod
    def create_or_find_by(cls, **kwargs):
        models = cls.objects
        for k, v in kwargs.items():
            models = models.filter(**{k: v})
        model = models.first()
        if not model:
            model = cls(**kwargs)
            model.save()
        return model

    @classmethod
    def state_zhcn(cls, state):
        return '有效' if state == 0 else '无效'

    class Meta:
        abstract = True
        

class CreatedAndUpdatedModel(BaseModel):
    
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True, auto_now=False)
    update_time = models.DateTimeField('修改时间', null=False, auto_now_add=True, auto_now=True)

    class Meta:
        abstract = True    


################## 权限相关表格 ##################

def update_last_login(sender, user, **kwargs):
    """
    A signal receiver which updates the last_login date for
    the user logging in.
    """
    user.last_login = timezone.now()
    user.save(update_fields=['last_login'])


user_logged_in.connect(update_last_login)


class AuthUserManager(BaseUserManager):

    def _create_user(self, username, email, password, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        username = self.model.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fields)
        user.set_password(password)
        user.full_clean()
        user.save(using=self._db)
        return user

    def create_user(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, email, password, **extra_fields)

    def create_superuser(self, username, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(username, email, password, **extra_fields)


class AuthUser(AbstractBaseUser):
    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    is_superuser = models.BooleanField(
        _('superuser status'),
        default=False,
        help_text=_(
            'Designates that this user has all permissions without '
            'explicitly assigning them.'
        ),
    )

    objects = AuthUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'username'

    def reset_password(self):
        self.password = self.DEFAULT_PASSWORD
        return self

    def to_option_dict(self):
        return dict(
                id=self.id,
                label=self.username
            )

    @property
    def superuser(self):
        return self.is_superuser

    def _build_token(self):
        if not hasattr(self, '_token'):
            s = '%s|%s|huanxicm' % (self.id, self.username)
            self._token = md5(s.encode('utf8')).hexdigest() + '|%s' % self.id
        return self._token
    
    @property
    def token(self):
        return self._build_token()
    
    @property
    def roles(self):
        return ['admin']

    def to_login_dict(self):
        return {
            'token': self.token,
        }

    def to_user_info_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'nickname': self.first_name,
            'roles': self.roles,
            'avatar': 'http://img3.imgtn.bdimg.com/it/u=3438414829,874981644&fm=26&gp=0.jpg'
        }

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = dict(
            id=self.id,
            username=self.username,
            token=self.token,
            date_joined=self.date_joined,
            last_login=self.last_login,
            full_name=self.get_full_name(),
            first_name=self.first_name,
            second_name=self.last_name,
        )
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                d[field] = [ f.to_dict() for f in fields.all() ]
        return d

    @property
    def is_noraml(self):
        return self.status == self.STATUS_NORMAL

    @property
    def is_disable(self):
        return self.status == self.STATUS_DISABLE

    def clean(self):
        super(AuthUser, self).clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name

    class Meta:
        db_table = 'auth_user'


class StateAndSiteModel(CreatedAndUpdatedModel):

    state = models.IntegerField('状态0有效1无效', max_length=11, default=0)
    site = models.IntegerField('暂时没用', max_length=11, default=0)

    def to_base_dict(self):
        return {
            'id': self.id,
            'create_time': self.create_time,
            'update_time': self.update_time,
            'state_cn': BaseModel.state_zhcn(self.state),
            'state': self.state,
            'site': self.site, 
        }

    class Meta:
        abstract = True


class Log(object):
    CREATE, UPDATE, DELETE, RELATION, RESTFUL = 1, 2, 3, 4, 5


class Operator(BaseModel):
    STATUS_NORMAL, STATUS_DISABLE = 0, 1

    loginname = models.CharField('登录名', max_length=64, null=False, default='', db_index=True)
    username = models.CharField('中文名', max_length=64, null=False, default='', db_index=True)
    password = models.CharField('登录密码', max_length=64, null=False, default='', db_index=True)
    created_at = models.DateTimeField('创建时间', null=False, auto_now=False, auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', null=False, auto_now=False, auto_now_add=True)
    status = models.IntegerField('状态', null=False, default=STATUS_NORMAL)

    def reset_password(self):
        self.password = self.DEFAULT_PASSWORD
        return self

    def to_option_dict(self):
        return dict(
                id=self.id,
                label=self.username
            )

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        s = '%s|%s|huanxicm' % (self.id, self.loginname)
        d = dict(
            id=self.id,
            loginname=self.loginname,
            username=self.username,
            token=md5(s.encode('utf8')).hexdigest() + '|%s' % self.id,
            updated_at=self.updated_at,
            created_at=self.created_at,
            statusCN=BaseModel.state_zhcn(self.status),
            status=self.status
        )
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                d[field] = [ f.to_dict() for f in fields.all() ]
        return d

    @property
    def is_noraml(self):
        return self.status == self.STATUS_NORMAL

    @property
    def is_disable(self):
        return self.status == self.STATUS_DISABLE

    class Meta:
        db_table = 'operators_v2'


class Team(BaseModel):
    NO_ORDER, ORDERING = 0, 1

    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('团队名', max_length=64, unique=True, blank=True)
    description = models.CharField('团队描述', max_length=512, unique=False, blank=True)
    contacts = models.CharField('联系人', max_length=64, default='', blank=True)
    contact_number1 = models.CharField('联系电话1', max_length=64, default='', blank=True)
    contact_number2 = models.CharField('联系电话2', max_length=64, default='', blank=True)
    contact_number3 = models.CharField('联系电话3', max_length=64, default='', blank=True)
    wechat = models.CharField('微信号', max_length=64, default='', blank=True)
    qq = models.CharField('qq', max_length=64, default='', blank=True)
    score = models.FloatField('得分', null=False, default=0.0)
    state = models.IntegerField('接单状态:0未接单,1已接单', null=False, default=0)
    created_at = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    updated_at = models.DateTimeField('修改时间', null=False, auto_now_add=True, auto_now=True)

    @property
    def state_cn(self):
        return '未接单' if self.state == 0 else '已接单'

    def to_option_dict(self):
        return dict(
                id=self.id,
                label=self.name
            )

    @property
    def video_order_id(self):
        return self._videoorder.order_id if self._videoorder else ''
    
    @property
    def video_order_operator_name(self):
        return self._videoorder.operator.username if self._videoorder and self._videoorder.operator else ''

    @property
    def _videoorder(self):
        if not hasattr(self, '_videoorder'):
            self._videoorder = VideoOrder.objects.filter(team_id=self.id).first()
        print(self._videoorder)
        return self._videoorder

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'state': self.state,
            'state_cn': self.state_cn,
            'created_at': self.created_at,
            'contacts': self.contacts,
            'score': self.score,
            'contact_number1': self.contact_number1,
            'contact_number2': self.contact_number2,
            'contact_number3': self.contact_number3,
            'wechat': self.wechat,
            'qq': self.qq
        }
        
        return d

    class Meta:
        db_table = 'teams'
        

# 影片时长表格，因为每个视频下单的价格受到时长的影响，所以单独提出来
class VideoTime(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('名称，比如1分钟、15分钟', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField('状态0为有效', max_length=11)
    factor = models.FloatField('价格因子', null=False, default=0.0)
    show_order = models.IntegerField(max_length=11)

    def to_dict(self, photo_style=''):
        return dict(
            value=self.id,
            label=self.name,
            factor=self.factor,
            state=self.state,
            show_order=self.show_order,
            create_time=self.create_time
        )

    class Meta:
        db_table = 'app_videotime'


# banner
class Advertisement(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('banner name', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    category_id = models.IntegerField('暂时没用', max_length=11)
    image_file = models.CharField('图片路径', max_length=255, unique=False, blank=True)
    url = models.CharField('跳转地址可配', max_length=255, unique=False, blank=True)
    state = models.IntegerField('状态0为有效', max_length=11)
    site = models.IntegerField('暂时没用', max_length=11)
    type = models.IntegerField('0小程序内连接，1H5', max_length=11)
    show_order = models.IntegerField(max_length=11)

    @property
    def type_cn(self):
        if self.type == 0:
            return '小程序内连接'
        elif self.type == 1:
            return 'H5'
        return ''

    @property
    def category_cn(self):
        return '首页' if self.category_id == 1 else '视频馆'

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return {
            'id': self.id,
            'name': self.name,
            'image_file': self.image_file,
            'url': self.url,
            'type': self.type,
            'type_cn': self.type_cn,
            'site': self.site,
            'state': self.state,
            'state_cn': BaseModel.state_zhcn(self.state),
            'show_order': self.show_order,
            'create_time': self.create_time,
            'category_id': self.category_id,
            'category_cn': self.category_cn
        }

    class Meta:
        db_table = 'app_advertisement'
            

# tag
class Tag(BaseModel):
    name = models.CharField('标签名称', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)

    @classmethod
    def all_valid_tags(cls):
        return cls.objects.filter(state=0).order_by('show_order').all()

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return dict(
            id=self.id,
            name=self.name,
            state=self.state,
            stateCN= '有效' if self.state == 0 else '无效',
            show_order=self.show_order,
            create_time=self.create_time
        )

    class Meta:
        db_table = 'app_tag'


# 价格类型
class PriceType(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('名称', max_length=256, unique=False, blank=True)
    desc = models.CharField('描述', max_length=256, unique=False, blank=True)
    icon = models.CharField('图标', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(max_length=11)
    type = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)

    def to_dynamic_form_dict(self, m2m_fields=[]):
        d = {
            "type": "select",
            "label": self.name,
            "value": "",
            'disabled': False,
            'multiple': False,
            'multipleLimit': 1,
            "rules": [],
            "key": str(self.id),
            "options": []
        }
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if field == 'pricetypedetail_set':
                d['options'] = [ ptd.to_option_dict() for ptd in fields.all() ]
        return d


    def to_options_dict(self):
        return {
            'label': self.name,
            'value': self.id
        }

    def to_autocomplete_dict(self):
        d = self.to_dict()
        d['value'] = ','.join([self.name, str(self.id)])
        return d

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = dict(
            id=self.id,
            name=self.name,
            desc=self.desc,
            type=self.type,
            icon=self.icon,
            showOrder=self.show_order,
            vmodel='form.priceType.' + self.name
        )
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                d[field] = [f.to_dict() for f in fields.all()]
        return d

    class Meta:
        db_table = 'app_pricetype'


# 价格子选项
class PriceTypeDetail(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('选项名称', max_length=256, unique=False, blank=True)
    desc = models.CharField('描述', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)
    price = models.IntegerField('原价', max_length=11)
    transaction_price = models.IntegerField('优惠价格', max_length=11)
    
    price_type = models.ManyToManyField(PriceType, through='PriceTypePriceTypeDetail')

    @property
    def price_type_name(self):
        if not hasattr(self, '_price_type_name'):
            pt = self.price_type.first()
            # self._price_type_name = self.price_type.name if self.price_type else ''
            self._price_type_name = pt.name if pt else ''
        return self._price_type_name

    @property
    def price_type_id(self):
        if not hasattr(self, '_price_type_id'):
            pt = self.price_type.first()
            self._price_type_id = pt.id if pt else ''
        return self._price_type_id

    def to_option_dict(self):
        return {
            'value': str(self.id),
            'label': self.name,
            'disabled': False
        }

    def to_tree_dict(self):
        return {
            'label': self.name+'|原价:'+ self.price+'|优惠价格:'+ self.transaction_price,
            'value': self.id
        }

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = dict(
            id=self.id,
            name=self.name,
            desc=self.desc,
            price=self.price,
            transaction_price=self.transaction_price,
            create_time=self.create_time,
            show_order=self.show_order,
            price_type_name=self.price_type_name,
            price_type_id=self.price_type_id,
            state=self.state
        )
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                if field == 'price_type':
                    price_type_in_db = fields.first()
                    d[field] =  price_type_in_db.to_dict() if price_type_in_db else {}
                else:
                    d[field] = [f.to_dict() for f in fields.all()]
        return d

    class Meta:
        db_table = 'app_pricetypedetail'


class PriceTypePriceTypeDetail(models.Model):
    pricetype = models.ForeignKey(PriceType, on_delete=models.CASCADE)
    pricetypedetail = models.ForeignKey(PriceTypeDetail, on_delete=models.CASCADE)

    @classmethod
    def deletePriceTypeDetailRel(cls, price_type_detail):
        type_detail_relationship = PriceTypePriceTypeDetail.objects.filter(pricetypedetail=price_type_detail).all()
        if type_detail_relationship:
            type_detail_relationship.delete()

    def to_dict(self):
        return {
            'id': self.id,
            'price_type_id': self.pricetype.id,
            'price_type_detail_id': self.pricetypedetail.id
        }

    class Meta:
        db_table = 'app_pricetype_price_type_detail'
            


# 视频类型，宣传片、广告片、微电影、三维动画
class VideoType(CreatedAndUpdatedModel):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('视频类型', max_length=256, unique=False, blank=True)
    state = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)

    def to_detail_dict(self, m2m_fields=[]):
        d = dict(
            value=self.id,
            label=self.name,
        )
        return d

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = {
            'id': self.id,
            'name': self.name,
            'showOrder': self.show_order
        }
        return d
            
    class Meta:
        db_table = 'app_videotype'


class VideoOrderType(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    city = models.CharField('城市', max_length=256, unique=False, blank=True)
    second_city = models.CharField('城市', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)
    price_type_detail = models.ManyToManyField(PriceTypeDetail, verbose_name='价格子选项', null=True, default='', blank='')
    video_time = models.ForeignKey(VideoTime, verbose_name='视频类型', null=True, default=-1, blank=-1, on_delete=models.SET_DEFAULT)

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        rslt = dict(
            id=self.id,
            city=self.city,
            second_city=self.second_city,
            state=self.state,
            show_order=self.show_order,
            video_time_name=self.video_time.name,
            create_time=self.create_time,
            video_time_id=self.video_time_id
        )

        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                rslt[field] = [f.to_dict() for f in fields.all()]

        for field in o2o_fields:
            field_value = getattr(self, field, None)
            if field_value:
                rslt[field] = field_value.to_dict()

        return rslt;

    class Meta:
        db_table = 'app_videoordertype'


class AppUser(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    openid = models.CharField('openid', max_length=64, unique=True, blank=False)
    nickName = models.CharField('昵称', max_length=256, unique=False, blank=True)
    gender = models.IntegerField(max_length=11)
    language = models.CharField('语言', max_length=256, unique=False, blank=True)
    city = models.CharField('城市', max_length=256, unique=False, blank=True)
    province = models.CharField('省份', max_length=256, unique=False, blank=True)
    country = models.CharField('国家', max_length=256, unique=False, blank=True)
    avatarUrl = models.CharField('头像', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return {
            'id': self.id,
            'nickName': self.nickName,
            'openid': self.openid,
            'gender': self.gender,
            'city': self.city,
            'province': self.province,
            'country': self.country,
            'avatarUrl': self.avatarUrl,
            'create_time': self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            'update_time': self.update_time.strftime("%Y-%m-%d %H:%M:%S")
        }

    class Meta:
        db_table = 'app_appuser'


class VideoOrderState(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('名称', max_length=256, unique=False, blank=True)

    def to_option_dict(self):
        return dict(
                id=self.id,
                label=self.name
            )

    def to_dict(self):
        return dict(
            id=self.id,
            name=self.name,
        )

    class Meta:
        db_table = 'app_videoorderstate'


class VideoOrder(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    city = models.CharField('城市', max_length=256, unique=False, blank=True)
    second_city = models.CharField('城市', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.ForeignKey(VideoOrderState, verbose_name='订单状态', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    video_type = models.ForeignKey(VideoType, verbose_name='视频类型', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    price_type_detail = models.ManyToManyField(PriceTypeDetail, verbose_name='价格子选项', null=True, default='', blank='')
    video_time = models.ForeignKey(VideoTime, verbose_name='视频类型', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    requirement = models.CharField('需求', max_length=256, unique=False, blank=True)
    contacts = models.CharField('城市', max_length=256, unique=False, blank=True)
    phone = models.CharField('电话', max_length=256, unique=False, blank=True)
    openid = models.CharField('openid', max_length=64, unique=False, blank=True)
    weixin_order_id = models.CharField('微信订单id', max_length=64, unique=False, blank=True)
    order_id = models.CharField('商户订单id', max_length=64, unique=False, blank=True)

    price = models.FloatField('待支付价格', max_length=11, default=0.0)
    pay_amount = models.FloatField('已支付金额', max_length=11, default=0.0)
    back_amount = models.FloatField('已退款价格', max_length=11, default=0.0)

    remark = models.CharField('备注', max_length=512, unique=False, blank=True)
    tax_unit = models.CharField('发票单位', max_length=512, unique=False, blank=True)
    tax_code = models.CharField('税号', max_length=512, unique=False, blank=True)
    agree_show = models.IntegerField('是否可以在平台展示', max_length=11, default=0)
    need_tax = models.IntegerField('是否可以在平台展示', max_length=11, default=0)
    back_remark = models.CharField('备注', max_length=512, unique=False, blank=True)
    team_id = models.IntegerField('团队ID', max_length=11, default=0)
    operator = models.ForeignKey(Operator, verbose_name='项目经理', null=True, default=None, on_delete=models.DO_NOTHING)
    # team = models.ForeignKey(Team, verbose_name='执行团队', null=True, default=None, on_delete=models.DO_NOTHING)

    def get_id(self):
        return dict(
            id=self.id,
        )

    @property
    def user_nickname(self):
        app_user = AppUser.objects.filter(openid=self.openid).first()
        if not app_user:
            return ''
        return app_user.nickName

    @property
    def operator_info(self):
        o = Operator.objects.filter(id=self.operator_id).first()
        if not o:
            return {'id': '', 'username': '未指派'}
        return o.to_dict()

    @property
    def team_info(self):
        t = Team.objects.filter(id=self.team_id).first()
        if not t:
            return {'id': '', 'name': '未指派'}
        return t.to_dict()

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = dict(
            id=self.id,
            city=self.city,
            second_city=self.second_city,
            create_time=self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            # url=self.url,
            price=self.price,
            pay_amount=self.pay_amount,
            back_amount=self.back_amount,
            state_code=self.state.id,
            state_name=self.state.name,
            requirement=self.requirement,
            contacts=self.contacts,
            phone=self.phone,
            remark=self.remark,
            tax_unit=self.tax_unit,
            order_id=self.order_id,
            tax_code=self.tax_code,
            agree_show=self.agree_show,
            need_tax=self.need_tax,
            back_remark=self.back_remark,
            user_nickname=self.user_nickname
        )
        # if type == 1:
        d['operator'] = self.operator_info
        d['operator_name'] = '指派经理' if not d['operator']['id'] else d['operator']['username']
        d['team'] = self.team_info
        d['team_name'] = '指派团队' if not d['team']['id'] else d['team']['name']
        d['video_type'] = self.video_type.to_dict()
        d['video_time'] = self.video_time.to_dict()
        d['total_price'] = 0
        d['transaction_price'] = 0
        d['price_detail'] = []
        for detail in self.price_type_detail.all():
            d['total_price'] += detail.price
            d['transaction_price'] += detail.transaction_price
            d['price_detail'].append( detail.to_dict(m2m_fields=['price_type']))
        d['total_price'] = d['total_price'] * self.video_time.factor
        d['transaction_price'] = d['transaction_price'] * self.video_time.factor
        return d

    class Meta:
        db_table = 'app_videoorder'


class GoodsCategory(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('类别', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField('状态', max_length=11)
    show_order = models.IntegerField('默认排序', max_length=11)

    def to_dict(self):
        d = {
            'value': self.id,
            'label': self.name,
        }
        return d

    class Meta:
        db_table = 'app_goodscategory'


class Video(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    title = models.CharField('标题', max_length=256, unique=False, blank=True)
    sub_title = models.CharField('标题', max_length=256, unique=False, blank=True)
    content = models.CharField('副标题下面的说明', max_length=512, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    image_file = models.CharField('封面', max_length=255, unique=False, blank=True)
    url = models.CharField('视频地址', max_length=255, unique=False, blank=True)
    state = models.IntegerField('0有效1无效', max_length=11)
    site = models.IntegerField('区分站点(无效字段)',max_length=11)
    show_order = models.IntegerField('显示顺序', max_length=11)
    play_time = models.IntegerField('播放次数', max_length=11, default=0)
    desc = models.CharField('描述：积分抵扣、分享有利', max_length=1024, default='')
    sub_desc = models.CharField('子描述：积分可抵扣10元、分享3人获取优惠券', max_length=1024, default='')
    ini_play_time = models.IntegerField('初始化播放次数', max_length=11, default=0)
    video_type_id = models.IntegerField('关联的视频类型', max_length=11, default=0)
    ini_play_time = models.IntegerField('初始化播放次数', max_length=11, default=0)


    video_type = models.IntegerField('是否是团队样片0不是1是', max_length=11, default=0)
    user_price = models.IntegerField('团队样片的用户价格，或者是单品的用户价格', max_length=11, default=0)
    team_price = models.IntegerField('整包价格', max_length=11, default=0)
    price_type = models.IntegerField('1单品2样片', max_length=11, default=1)
    detail = models.CharField('单品详情的图片地址', max_length=2048, default='')
    tag = models.CharField('标签多个用因为逗号隔开，比如7天包邮，货到付款类似的描述信息', max_length=1024, default='')
    sold_num = models.IntegerField('实际下单人数', max_length=11, default=1)
    ini_sold_num = models.IntegerField('初始化下单人数', max_length=11, default=1)
    price_unit = models.CharField('单品的计价单位比如：人、天', max_length=1024, default='')
    tips = models.CharField('提示', max_length=1024, default='')
    team_id = models.IntegerField('团队id', max_length=11, default=1)
    shoot_day = models.IntegerField('拍摄时间单位天', max_length=11, default=1)
    video_duration = models.IntegerField('成片时长单位分钟', max_length=11, default=1)

    def get_cn_key(self, field):
        return '%s_cn' % field

    @property
    def related_video_type(self):
        if not self.video_type_id:
            return None
        if not hasattr(self, '_related_video_type'):
            self._related_video_type = VideoType.objects.filter(id=self.video_type_id).first()
        return self._related_video_type

    def to_dict(self, m2m_fields=[], o2o_fields=[],):
        d = dict(
            id=self.id,
            title=self.title,
            image_file=self.image_file,
            url=self.url,
            create_time=self.create_time,
            play_time=self.play_time,
            desc=self.desc,
            tag=self.tag,
            user_price=self.user_price,
            team_price=self.team_price,
            state=self.state,
            stateCN='有效' if self.state == 0 else '无效',
            show_order=self.show_order,
            video_type_id=self.video_type_id,
            video_type_name=self.related_video_type.name if self.related_video_type else ''
        )
        return d

    class Meta:
        db_table = 'app_video_v2'


class GoodsBanner(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('类别', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField('状态', max_length=11)
    site = models.IntegerField(max_length=11)
    show_order = models.IntegerField('默认排序', max_length=11)
    url = models.CharField('链接地址', max_length=255, unique=False, blank=True)

    def to_dict(self):
        d = {
            'url': self.url,
            'name': self.name,
        }
        if self.url:
            d['url'] += '/750'
        return d

    class Meta:
        db_table = 'app_goodsbanner'


class GoodsPrice(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('类别', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField('状态', max_length=11)
    site = models.IntegerField(max_length=11)
    show_order = models.IntegerField('默认排序', max_length=11)
    price = models.IntegerField('原始价格', max_length=11)
    transaction_price = models.IntegerField('折后价格', max_length=11)
    unit = models.CharField('单位', max_length=256, unique=False, blank=True)
    inventory = models.IntegerField('库存', max_length=11)

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return {
            'value': self.id,
            'label': self.name,
            'price': self.price,
            'transaction_price': self.transaction_price,
            'unit': self.unit,
            'inventory': self.inventory,
            'show_order': self.show_order,
            'state': self.state,
            'stateCN': BaseModel.state_zhcn(self.state),
            'create_time': self.create_time,
            'site': self.site
        }

    class Meta:
        db_table = 'app_goodsprice'

class Goods(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('标题', max_length=256, unique=False, blank=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    image_file = models.CharField('封面', max_length=255, unique=False, blank=True)
    tags = models.CharField('标签', max_length=255, unique=False, blank=True)
    state = models.IntegerField(max_length=11)
    site = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)
    sales = models.IntegerField(max_length=11)
    detail = models.CharField('链接地址', max_length=255, unique=False, blank=True)
    content = models.CharField('链接地址', max_length=512, unique=False, blank=True)
    city = models.CharField('城市', max_length=512, unique=False, blank=True)
    category = models.ForeignKey(GoodsCategory, verbose_name='分类', null=True, default=-1, blank=-1, on_delete=models.SET_DEFAULT)
    
    banner = models.ManyToManyField(GoodsBanner, verbose_name='分类', null=True, default='', blank='')
    price = models.ManyToManyField(GoodsPrice, through='GoodsPriceRelation')

    @property
    def _first_goods_price(self):
        first_goods_price = self.price.order_by('show_order').first()
        return first_goods_price if first_goods_price else None

    @property
    def goods_prices(self):
        return [ p.to_dict() for p in self.price.all() ]

    @property
    def banners(self):
        return [ {'url': b.url } for b in self.banner.all() ]

    @property
    def detail_pics(self):
        detail_list = self.detail.split(',')
        return [ {'url': d.strip() } for d in detail_list if d.strip() ]
    
    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = {
            'id': self.id,
            'category_id': self.category_id,
            'name': self.name,
            'banners': self.banners,
            'image_file': self.image_file,
            'tags_display': self.tags,
            'tags': [ t.strip() for t in self.tags.split(',') if t.strip() ],
            'sales': self.sales,
            'detail': self.detail_pics,
            'site': self.site,
            'city': self.city,
            'content': self.content,
            'state': self.state,
            'stateCN': '已上架' if self.state == 0 else '已下架',
            'goods_prices': self.goods_prices,
            'show_order': self.show_order,
            'price': 0,
            'transaction_price': 0,
            'inventory': 0,
            'unit': ''
        }
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                d[field] = [f.to_dict() for f in fields.all()]

        if self._first_goods_price:
            d['price'] = self._first_goods_price.price
            d['transaction_price'] = self._first_goods_price.transaction_price
            d['inventory'] = self._first_goods_price.inventory
            d['unit'] = self._first_goods_price.unit

        return d

    class Meta:
        db_table = 'app_goods'


class GoodsPriceRelation(models.Model):
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE)
    goodsprice = models.ForeignKey(GoodsPrice, on_delete=models.CASCADE)

    @classmethod
    def deleteGoodsPrice(cls, goods_price):
        goods_price_relationship = GoodsPriceRelation.objects.filter(goodsprice=goods_price).all()
        if goods_price_relationship:
            goods_price_relationship.delete()

    @classmethod
    def deleteGoods(cls, goods):
        goods_price_relationship = GoodsPriceRelation.objects.filter(goods=goods).all()
        if goods_price_relationship:
            goods_price_relationship.delete()

    class Meta:
        db_table = 'app_goods_price'


# 商品评论
class GoodsComment(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(max_length=11)
    site = models.IntegerField(max_length=11)
    goods_id = models.IntegerField(max_length=11)
    show_order = models.IntegerField(max_length=11)
    content = models.CharField('链接地址', max_length=512, unique=False, blank=True)
    price = models.ForeignKey(GoodsPrice, verbose_name='分类', null=True, default=-1, blank=-1, on_delete=models.SET_DEFAULT)
    user = models.ForeignKey(AppUser, verbose_name='评论者', null=True, default=-1, blank=-1, on_delete=models.SET_DEFAULT)

    def to_dict(self, photo_style=''):
        d = {
            'id': self.id,
            'create_time': self.create_time,
            'content': self.content,

        }
        if self.price:
            d['type'] = self.price.to_dict()

        if self.user:
            d['user'] = self.user.to_dict()

        return d


class GoodsOrder(models.Model):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.ForeignKey(VideoOrderState, verbose_name='订单状态', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    goods = models.ForeignKey(Goods, verbose_name='视频类型', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    good_price = models.ForeignKey(GoodsPrice, verbose_name='视频类型', null=True, default=-1, blank=-1, on_delete=models.DO_NOTHING)
    openid = models.CharField('openid', max_length=64, unique=False, blank=True)
    weixin_order_id = models.CharField('微信订单id', max_length=64, unique=False, blank=True)
    order_id = models.CharField('商户订单id', max_length=64, unique=False, blank=True)
    num = models.IntegerField(max_length=11, default=1)
    price = models.FloatField('待支付价格', max_length=11, default=0.0)
    pay_amount = models.FloatField('已支付金额', max_length=11, default=0.0)
    remark = models.CharField('备注', max_length=512, unique=False, blank=True)

    def get_id(self):
        return dict(
            id=self.id,
        )

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = dict(
            id=self.id,
            price=self.price,
            pay_amount=self.pay_amount,
            order_id=self.order_id,
            weixin_order_id=self.weixin_order_id,
            create_time=self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            remark=self.remark,
            num=self.num
        )
        if self.good_price:
            d['goods_price'] = self.good_price.to_dict()
        if self.goods:
            d['goods'] = self.goods.to_dict()
        if self.state:
            d['state'] = self.state.to_dict()
        return d

    class Meta:
        db_table = 'app_goodsorder'

################## 权限相关表格 ##################
class Resource(BaseModel):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    parent_id = models.IntegerField('父节点id', null=True, default=None)
    name = models.CharField('资源名称', max_length=64, unique=False, default='', blank=True)
    description = models.CharField('资源描述', max_length=512, unique=False, blank=True)
    url = models.CharField('地址', max_length=512, unique=False, blank=True)
    permission = models.CharField('菜单编码', max_length=50, unique=False, blank=True)
    icon = models.CharField('菜单图标', max_length=255, unique=False, blank=True)
    cate = models.IntegerField('类型:0:菜单,1:按钮', null=False, default=0)
    show_order = models.IntegerField('排序号', null=False, default=1)
    disabled = models.IntegerField('是否启用', null=False, default=0, db_index=True)
    created_at = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    updated_at = models.DateTimeField('修改时间', null=False, auto_now_add=True, auto_now=True)

    @classmethod
    def to_tree(cls):
        rslt = []
        for l1 in cls.objects.filter(parent_id__isnull=True).all():
            d1 = l1.to_tree_dict()
            rslt.append(d1)
            for l2 in l1.sub_cates:
                d2 = l2.to_tree_dict()
                d1['children'].append(d2)
                for l3 in l2.sub_cates:
                    d3 = l3.to_tree_dict()
                    del d3['children']
                    d2['children'].append(d3)
        return rslt

    @property
    def disabled_cn(self):
        return '启用' if self.disabled == 0 else '禁用'

    @property
    def sub_cates(self):
        if not hasattr(self, '_sub_cates'):
            self._sub_cates = self._get_sub_cates()
        return self._sub_cates

    def _get_sub_cates(self):
        objs = self.__class__.objects.filter(parent_id=self.id)
        return objs.all()

    def to_option_dict(self):
        return {
            'value': self.id,
            'label': self.name
        }

    def to_tree_dict(self):
        return dict(
            value = self.id,
            label = self.name,
            children = []
        )

    @classmethod
    def to_menu(cls, resource_ids):
        rslt = []
        for l1 in cls.objects.filter(parent_id__isnull=True).all():
            d1 = l1.to_menu_dict()
            if l1.id in resource_ids:
                rslt.append(d1)
            for l2 in l1.sub_cates:
                d2 = l2.to_menu_dict()
                if l2.id in resource_ids:
                    if d1 not in rslt:
                        rslt.append(d1)
                    d1['subs'].append(d2)
                for l3 in l2.sub_cates:
                    d3 = l3.to_menu_dict()
                    del d3['subs']
                    if l3.id in resource_ids:
                        if d1 not in rslt:
                            rslt.append(d1)
                        if d2 not in d1:
                            d1['subs'].append(d2)
                        d2['subs'].append(d3)
                if not d2['subs']:
                    del d2['subs']
            
        return rslt

    def to_menu_dict(self):
        return {
                'icon': self.icon,
                'title': self.name,
                'index': self.url if self.url else str(self.show_order),
                'subs': []
            }

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'cate': self.cate,
            'cate_cn': '菜单' if self.cate == 0 else '按钮',
            'url': self.url,
            'icon': self.icon,
            'parent_id': self.parent_id,
            'permission': self.permission,
            'show_order': self.show_order,
            'disabled': self.disabled,
            'disabled_cn': self.disabled_cn,
            'created_at': self.created_at
        }

    class Meta:
        db_table = 'resources_v2'


class Role(BaseModel):
    id = models.AutoField('主键id', max_length=11, primary_key=True)
    name = models.CharField('角色名', max_length=64, unique=True, blank=True)
    description = models.CharField('角色描述', max_length=512, unique=False, blank=True)
    show_order = models.IntegerField('排序号', null=False, default=1)
    disabled = models.IntegerField('是否启用', null=False, default=0, db_index=True)
    created_at = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    updated_at = models.DateTimeField('修改时间', null=False, auto_now_add=True, auto_now=True)

    resources = models.ManyToManyField(Resource, verbose_name='资源', null=True, through='RoleResource')
    operators = models.ManyToManyField(Operator, verbose_name='成员', null=True, through='RoleOperator')

    @property
    def disabled_cn(self):
        return '启用' if self.disabled == 0 else '禁用'

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'show_order': self.show_order,
            'disabled': self.disabled,
            'disabled_cn': self.disabled_cn,
            'created_at': self.created_at
        }
        for field in m2m_fields:
            fields = getattr(self, field, [])
            if fields:
                d[field] = [f.to_dict() for f in fields.all()]
        return d

    class Meta:
        db_table = 'roles_v2'

        
class RoleOperator(BaseModel):
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    operator = models.ForeignKey(Operator, on_delete=models.CASCADE)

    class Meta:
        db_table = 'roles_operators_v2'


class RoleResource(BaseModel):
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE)

    class Meta:
        db_table = 'roles_resources_v2'
            



class Series(StateAndSiteModel):
    name = models.CharField('名称', max_length=256, null=False, default='')

    class Meta:
        db_table = 'app_series_v2'


class SeriesVideo(StateAndSiteModel):
    video = models.ForeignKey(Video, db_column='vid', on_delete=models.CASCADE)
    series = models.ForeignKey(Series, on_delete=models.CASCADE)
    show_order = models.IntegerField('排序号', null=False, default=1)
    img_url = models.CharField('单品或者子系列的图片', max_length=256, null=False, default='')
    type = models.IntegerField('1视频2系列（系列里面有可能是子系列有可能是视频）', null=False, default=0)

    class Meta:
        db_table = 'app_series_video_v2'


class Category(StateAndSiteModel):
    name = models.CharField('角色或者设备名称', max_length=256, null=False, default='')
    show_order = models.IntegerField('排序号', null=False, default=1)
    
    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = super(Category, self).to_base_dict()
        d['name'] = self.name
        d['show_order'] = self.show_order
        return d

    class Meta:
        db_table = 'app_category_v2'  


class CategoryOption(StateAndSiteModel):
    title = models.CharField('标题', max_length=256, null=False, default='')
    show_order = models.IntegerField('排序按照升序排列', null=False, default=1)
    desc = models.CharField('描述', max_length=256, null=False, default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        d = super(CategoryOption, self).to_base_dict()
        d['title'] = self.title
        d['show_order'] = self.show_order
        d['desc'] = self.desc
        d['category_id'] = self.category.id
        return d

    class Meta:
        db_table = 'app_category_option_v2'


class Element(StateAndSiteModel):
    name = models.CharField('角色或者设备名称', max_length=256, null=False, default='')
    unit = models.CharField('单位', max_length=256, null=False, default='')
    show_order = models.IntegerField('排序号', null=False, default=1)
    price = models.IntegerField('计算价格', null=False, default=0)
    commission_price = models.IntegerField('佣金价格，派单用到', null=False, default=0)
    is_ignore = models.IntegerField('是否可以忽略', null=False, default=0)    
    type = models.IntegerField('1角色2设备', null=False, default=1)    
    level = models.IntegerField('等级：初级1、中级2、高级3', null=False, default=1)    
    category = models.ForeignKey(Category, on_delete=models.CASCADE)    

    TYPE_ROLE, TYPE_EQUIPMENT = 1, 2
    PRIMARY_LEVEL, MEDIUM_LEVEL, SENIOR_LEVEL = 1, 2, 3

    LEVEL_DESC_DICT = {
        1: '初级',
        2: '中级',
        3: '高级',
    }

    @property
    def ignore_desc(self):
        return '是' if self.is_ignore == 1 else '否'

    @property
    def type_desc(self):
        return '角色' if self.type == 1 else '设备'

    @property
    def level_desc(self):
        return Element.LEVEL_DESC_DICT.get(self.level, '未定级别')

    def to_dict(self, m2m_fields=[], o2o_fields=[]):
        return {
            'id': self.id,
            'name': self.name,
            'unit': self.unit,
            'show_order': self.show_order,
            'price': self.price,
            'commission_price': self.commission_price,
            'is_ignore': self.is_ignore,
            'is_ignore_desc': self.ignore_desc,
            'type': self.type,
            'type_desc': self.type_desc,
            'level': self.level,
            'level_desc': self.level_desc,
        }

    class Meta:
        db_table = 'app_element_v2'


class OptionElement(StateAndSiteModel):
    option = models.ForeignKey(CategoryOption, on_delete=models.CASCADE)
    element = models.ForeignKey(Element, on_delete=models.CASCADE)
    show_order = models.IntegerField('排列', null=False, default=1)
    num = models.IntegerField('数量', null=False, default=0)

    class Meta:
        db_table = 'app_category_option_element_v2'


class Recommend(StateAndSiteModel):
    img_url = models.CharField('单品或者子系列的图片', max_length=256, null=False, default='')
    type = models.IntegerField('0单品1系列', null=False, default=0)
    video_or_series_id = models.IntegerField('单品或者系列的id', null=False, default=0)
    show_order = models.IntegerField('排列', null=False, default=1)

    class Meta:
        db_table = 'app_recommend_v2' 


class VideoTypeCategory(CreatedAndUpdatedModel):
    state = models.IntegerField('状态0有效1无效', max_length=11, default=0)
    show_order = models.IntegerField('排列', null=False, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    videotype = models.ForeignKey(VideoType, on_delete=models.CASCADE, db_column='video_type_id')

    class Meta:
        db_table = 'app_videotype_catogory_v2'
            

class VideoTag(BaseModel):
    video = models.ForeignKey(Video, on_delete=models.CASCADE)
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)

    class Meta:
        db_table = 'app_video_tags_v2'
            

class Group(CreatedAndUpdatedModel):
    name = models.CharField('角色名', max_length=64, unique=True, blank=True)
    description = models.CharField('角色描述', max_length=512, unique=False, blank=True)
    show_order = models.IntegerField('排序号', null=False, default=1)
    disabled = models.IntegerField('是否启用', null=False, default=0, db_index=True)

    class Meta:
        db_table = 'auth_group'


class Permission(CreatedAndUpdatedModel):
    parent_id = models.IntegerField('父节点id', null=True, default=None)
    name = models.CharField('资源名称', max_length=64, unique=False, default='', blank=True)
    description = models.CharField('资源描述', max_length=512, unique=False, blank=True)
    url = models.CharField('地址', max_length=512, unique=False, blank=True)
    permission = models.CharField('菜单编码', max_length=50, unique=False, blank=True)
    icon = models.CharField('菜单图标', max_length=255, unique=False, blank=True)
    cate = models.IntegerField('类型:0:菜单,1:按钮', null=False, default=0)
    show_order = models.IntegerField('排序号', null=False, default=1)
    disabled = models.IntegerField('是否启用', null=False, default=0, db_index=True)

    class Meta:
        db_table = 'auth_permission'


class GroupPermission(BaseModel):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE)

    class Meta:
        db_table = 'auth_group_permissions'


class UserGroup(BaseModel):
    user = models.ForeignKey(AuthUser, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)

    class Meta:
        db_table = 'auth_user_groups'
    
        

